package com.lal.sdk.util;

/**
 * @author gc
 * @date 2022/7/31
 **/

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Pattern;


public class IpUtil {
    private static final String UNKNOWN = "unknown";
    private static final String IPV6_LOCAL = "0:0:0:0:0:0:0:1";
    private static final String COMMA = ",";
    private static final String FE = "fe";
    private static final String[] IP_HEADS = new String[]{"x-forwarded-for", "X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP"};

    /**
     * 获取请求用户的IP地址
     *
     * @param request
     * @return
     */
    public static String getRequestIp(HttpServletRequest request) {
        String ip = null;
        for (String ipHead : IP_HEADS) {
            ip = request.getHeader(ipHead);
            if (ip!=null && !UNKNOWN.equalsIgnoreCase(ip)) {
                break;
            }
        }
        if (ip==null || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (IPV6_LOCAL.equals(ip)) {
            ip = getLocalhostIp();
        }
        return ip;
    }

    public static String getLocalhostIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 校验是否是有效的IPV4
     *
     * @param ipAddress
     * @return
     */
    public static boolean isValidIpV4(String ipAddress) {
        return Pattern.matches("^([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}$", ipAddress);
    }

}